---
import ImageWrapper from "@/components/misc/ImageWrapper.astro";
import { siteConfig } from "@/config";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import MainGridLayout from "@/layouts/MainGridLayout.astro";

// 检查页面是否启用
if (!siteConfig.pages.anime) {
  return Astro.redirect("/404/");
}

// 服务器端只传递配置信息到客户端
const BANGUMI_USER_ID = siteConfig.bangumi?.userId || "your-user-id";

// 收藏状态映射
const COLLECTION_TYPES = {
  1: { key: "wish", name: i18n(I18nKey.animeStatusWish), icon: "material-symbols:schedule", color: "amber" },
  2: { key: "done", name: i18n(I18nKey.animeStatusDone), icon: "material-symbols:check-circle", color: "blue" },
  3: { key: "doing", name: i18n(I18nKey.animeStatusDoing), icon: "material-symbols:play-circle", color: "green" },
  4: { key: "onhold", name: i18n(I18nKey.animeStatusOnhold), icon: "material-symbols:pause-circle", color: "orange" },
  5: { key: "dropped", name: i18n(I18nKey.animeStatusDropped), icon: "material-symbols:cancel", color: "red" },
} as const;
---

<MainGridLayout
  title={i18n(I18nKey.anime)}
  description={i18n(I18nKey.animeSubtitle)}
>
  <div
    class="flex w-full rounded-[var(--radius-large)] overflow-hidden relative min-h-32"
  >
    <div class="card-base z-10 px-9 py-6 relative w-full">
      <!-- 页面标题 -->
      <div class="relative w-full mb-8">
        <div class="mb-6">
          <h1 class="text-4xl font-bold text-black/90 dark:text-white/90 mb-2">
            {i18n(I18nKey.animeTitle)}
          </h1>
          <p class="text-black/75 dark:text-white/75">
            {i18n(I18nKey.animeSubtitle)}
          </p>
          <h2 class="text-black/75 dark:text-white/75">
            {i18n(I18nKey.animeRefreshNote)}
          </h2>
        </div>

        <!-- 筛选控件 -->
        <div class="mb-8">
          <div class="filter-container">
            <button class="filter-tag active" data-status="all">{i18n(I18nKey.animeStatusAll)}</button>
            <button class="filter-tag" data-status="doing">{i18n(I18nKey.animeStatusDoing)}</button>
            <button class="filter-tag" data-status="done">{i18n(I18nKey.animeStatusDone)}</button>
            <button class="filter-tag" data-status="wish">{i18n(I18nKey.animeStatusWish)}</button>
            <button class="filter-tag" data-status="onhold">{i18n(I18nKey.animeStatusOnhold)}</button>
            <button class="filter-tag" data-status="dropped">{i18n(I18nKey.animeStatusDropped)}</button>
          </div>
        </div>
      </div>

      <!-- 动漫列表 -->
      <div class="mb-8">
        <h2 class="text-2xl font-bold text-black/90 dark:text-white/90 mb-4">
          {i18n(I18nKey.animeList)}
        </h2>

        <!-- 加载状态 -->
        <div id="loadingState" class="text-center py-16">
          <div
            class="inline-flex items-center justify-center w-16 h-16 bg-[var(--btn-regular-bg)] rounded-full mb-6 border border-[var(--line-divider)]"
          >
            <div
              class="animate-spin w-8 h-8 border-3 border-[var(--primary)] border-t-transparent rounded-full"
            >
            </div>
          </div>
          <h3
            class="text-xl font-semibold text-black/80 dark:text-white/80 mb-3"
          >
            {i18n(I18nKey.animeLoading)}
          </h3>
          <p class="text-black/60 dark:text-white/60">
            {i18n(I18nKey.animeLoadingDescription)}
          </p>
        </div>

        <!-- 错误状态 -->
        <div id="errorState" class="hidden text-center py-16">
          <div
            class="inline-flex items-center justify-center w-16 h-16 bg-[var(--btn-regular-bg)] rounded-full mb-6 border border-[var(--line-divider)]"
          >
            <svg
              class="w-8 h-8 text-red-500"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
          </div>
          <h3 class="text-xl font-semibold text-red-500 mb-3">{i18n(I18nKey.animeError)}</h3>
          <p class="text-black/60 dark:text-white/60 mb-6">
            {i18n(I18nKey.animeErrorDescription)}
          </p>
          <button
            id="retryButton"
            class="btn-regular inline-flex items-center gap-2 px-6 py-3 rounded-xl transition-all duration-200 font-medium"
          >
            <svg
              class="w-4 h-4"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
              ></path>
            </svg>
            {i18n(I18nKey.animeRetry)}
          </button>
        </div>

        <!-- 空状态 -->
        <div id="emptyState" class="hidden text-center py-16">
          <div
            class="inline-flex items-center justify-center w-16 h-16 bg-[var(--btn-regular-bg)] rounded-full mb-6 border border-[var(--line-divider)]"
          >
            <svg
              class="w-8 h-8 text-[var(--btn-content)]"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"
              ></path>
            </svg>
          </div>
          <h3
            class="text-xl font-semibold text-black/80 dark:text-white/80 mb-3"
          >
            {i18n(I18nKey.animeEmptyData)}
          </h3>
          <p class="text-black/60 dark:text-white/60">
            {i18n(I18nKey.animeEmptyDescription)}
          </p>
          <p class="text-sm text-black/50 dark:text-white/50 mt-2">
            {i18n(I18nKey.animeEmptySuggestion)}
          </p>
        </div>

        <!-- 未配置状态 -->
        {
          BANGUMI_USER_ID === "your-user-id" ? (
            <div id="unconfiguredState" class="text-center py-12">
              <iconify-icon icon="material-symbols:settings" class="text-5xl mb-4 text-[var(--btn-content)]"></iconify-icon>
              <h3 class="text-xl font-medium text-black/80 dark:text-white/80 mb-2">
                {i18n(I18nKey.animeEmpty)}
              </h3>
              <p class="text-black/60 dark:text-white/60">
                {i18n(I18nKey.animeConfigDescription)}
              </p>
            </div>
          ) : null
        }

        <!-- 动漫列表容器 -->
        <div
          id="animeGrid"
          class="hidden grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 md:gap-6"
        >
          <!-- 动漫卡片将由 JavaScript 生成 -->
        </div>
      </div>

      <!-- 分页控件 -->
      <div id="paginationContainer" class="hidden">
        <div
          class="bg-gradient-to-r from-[var(--card-bg)] to-[var(--card-bg)] border border-[var(--line-divider)] rounded-[var(--radius-large)] p-4 md:p-6 mb-6 shadow-sm"
        >
          <div class="flex flex-col items-center gap-3 md:gap-4">
            <div
              id="pagination"
              class="flex justify-center items-center gap-1 md:gap-2 flex-wrap"
            >
              <!-- 分页按钮将由 JavaScript 生成 -->
            </div>

            <!-- 页面信息 -->
            <div
              id="pageInfo"
              class="flex items-center gap-2 text-xs md:text-sm text-[var(--btn-content)] bg-[var(--btn-regular-bg)] px-3 md:px-4 py-1.5 md:py-2 rounded-full border border-[var(--line-divider)]"
            >
              <iconify-icon icon="material-symbols:description" class="w-4 h-4"></iconify-icon>
              <!-- 页面信息文本将由 JavaScript 生成 -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</MainGridLayout>

<script
  define:vars={{
    BANGUMI_USER_ID,
    COLLECTION_TYPES,
    PAGINATION_FIRST: i18n(I18nKey.paginationFirst),
    PAGINATION_PREV: i18n(I18nKey.paginationPrev),
    PAGINATION_NEXT: i18n(I18nKey.paginationNext),
    PAGINATION_LAST: i18n(I18nKey.paginationLast),
    PAGINATION_PAGE: i18n(I18nKey.paginationPage),
    PAGINATION_OF: i18n(I18nKey.paginationOf),
    PAGINATION_TOTAL: i18n(I18nKey.paginationTotal),
    PAGINATION_RECORDS: i18n(I18nKey.paginationRecords),
    ANIME_YEAR: i18n(I18nKey.animeYear),
    ANIME_EPISODES: i18n(I18nKey.animeEpisodes),
    ANIME_RANK: i18n(I18nKey.animeRank),
    ANIME_UNKNOWN: i18n(I18nKey.animeUnknown),
    ANIME_LOAD_FAILED: i18n(I18nKey.animeLoadFailed),
  }}
>
  // 传递服务器端配置到客户端
  window.animePageConfig = {
    userId: BANGUMI_USER_ID,
    apiBase: "https://api.bgm.tv",
    collectionTypes: COLLECTION_TYPES,
    pageSize: 20,
    // 分页文本国际化
    pagination: {
      first: PAGINATION_FIRST,
      prev: PAGINATION_PREV,
      next: PAGINATION_NEXT,
      last: PAGINATION_LAST,
      page: PAGINATION_PAGE,
      of: PAGINATION_OF,
      total: PAGINATION_TOTAL,
      records: PAGINATION_RECORDS,
      year: ANIME_YEAR,
      episodes: ANIME_EPISODES,
      rank: ANIME_RANK,
      unknown: ANIME_UNKNOWN,
      loadFailed: ANIME_LOAD_FAILED,
    },
  };
</script>

<script is:inline>
  // 避免重复声明
  if (typeof window.AnimePageManager === 'undefined') {
    window.AnimePageManager = class AnimePageManager {
    constructor() {
      this.config = window.animePageConfig;
      this.currentPage = 1;
      this.statusFilter = "all";
      this.totalCount = 0;
      this.totalPages = 0;
      this.animeData = [];
      this.allStats = { total: 0, watching: 0, completed: 0, avgRating: 0 };

      this.init();
    }

    init() {
      // 检查是否配置了用户ID
      if (this.config.userId === "your-user-id") {
        this.showUnconfiguredState();
        return;
      }

      // 从URL参数获取初始状态
      this.parseUrlParams();

      // 初始化UI
      this.initializeUI();

      // 加载数据
      this.loadData();
    }

    parseUrlParams() {
      const urlParams = new URLSearchParams(window.location.search);
      this.currentPage = parseInt(urlParams.get("page") || "1");
      this.statusFilter = urlParams.get("status") || "all";
    }

    initializeUI() {
      this.renderFilterButtons();
      this.bindEvents();
    }

    renderFilterButtons() {
      // 静态HTML已处理筛选按钮，无需动态生成
    }

    bindEvents() {
      // 筛选按钮事件
      document.addEventListener("click", (e) => {
        const filterTag = e.target.closest(".filter-tag");
        if (filterTag) {
          e.preventDefault();

          // 移除其他按钮的active类
          document.querySelectorAll(".filter-tag").forEach((btn) => {
            btn.classList.remove("active");
          });

          // 添加active类到当前按钮
          filterTag.classList.add("active");

          const status = filterTag.dataset.status;
          this.changeFilter(status);
        }
      });

      // 重试按钮事件
      document.getElementById("retryButton")?.addEventListener("click", () => {
        this.loadData();
      });

      // 分页事件委托
      document.addEventListener("click", (e) => {
        // 查找最近的 page-btn 或 page-btn-mobile 元素
        const pageBtn = e.target.closest(".page-btn, .page-btn-mobile");
        if (pageBtn) {
          e.preventDefault();
          const page = parseInt(pageBtn.dataset.page);
          if (!isNaN(page)) {
            this.changePage(page);
          }
        }
      });

      // 窗口大小变化时重新渲染分页
      let resizeTimeout;
      window.addEventListener("resize", () => {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(() => {
          if (this.totalPages > 1) {
            this.renderPagination();
          }
        }, 150);
      });
    }

    async loadData() {
      try {
        this.showLoading();

        // 获取当前页数据
        const filterType =
          this.statusFilter === "all"
            ? undefined
            : Object.entries(this.config.collectionTypes).find(
                ([_, v]) => v.key === this.statusFilter
              )?.[0];

        const result = await this.fetchBangumiCollections({
          type: filterType ? parseInt(filterType) : undefined,
          limit: this.config.pageSize,
          offset: (this.currentPage - 1) * this.config.pageSize,
        });

        if (result.data && result.data.length > 0) {
          this.animeData = await this.processCollectionData(result.data);
          this.totalCount = result.total || result.data.length;
          this.totalPages = Math.ceil(this.totalCount / this.config.pageSize);

          this.renderAnimeGrid();
          this.renderPagination();
          this.showDataState();
        } else {
          // 没有数据时显示空状态
          this.animeData = [];
          this.totalCount = 0;
          this.totalPages = 0;
          this.showEmpty();
        }
      } catch (error) {
        console.error("Failed to load anime data:", error);
        this.showError(window.animePageConfig?.pagination?.loadFailed || "Load failed");
      }
    }

    async fetchBangumiCollections(options) {
      const params = new URLSearchParams({
        subject_type: "2", // 动画类型
        limit: options.limit.toString(),
        offset: options.offset.toString(),
      });

      if (options.type) {
        params.append("type", options.type.toString());
      }

      const response = await fetch(
        `${this.config.apiBase}/v0/users/${this.config.userId}/collections?${params}`
      );

      if (!response.ok) {
        throw new Error(`Bangumi API error: ${response.status}`);
      }

      return await response.json();
    }

    async processCollectionData(collections) {
      const processedData = await Promise.all(
        collections.map(async (item) => {
          // 获取详细信息
          const details = await this.fetchSubjectDetails(item.subject_id);

          const subject = item.subject || details;
          const collectionType = this.config.collectionTypes[item.type];

          return {
            id: item.subject_id,
            title: subject?.name_cn || subject?.name || "Unknown Title",
            originalTitle: subject?.name || "",
            cover:
              subject?.images?.large ||
              subject?.images?.medium ||
              "/assets/anime/default.webp",
            description: subject?.summary || subject?.short_summary || "",
            userRating: item.rate || 0,
            score: subject?.rating?.score || 0,
            rank: subject?.rating?.rank || 0,
            status: collectionType?.key || "unknown",
            statusText: collectionType?.name || window.animePageConfig?.pagination?.unknown || "Unknown",
            statusIcon: collectionType?.icon || "?",
            statusColor: collectionType?.color || "gray",
            progress: item.ep_status || 0,
            totalEpisodes: subject?.eps || 0,
            year: subject?.date ? new Date(subject.date).getFullYear() : 0,
            tags: subject?.tags?.slice(0, 5).map((tag) => tag.name) || [],
            link: `https://bgm.tv/subject/${item.subject_id}`,
            type: item.type,
            comment: item.comment || "",
          };
        })
      );

      return processedData;
    }

    async fetchSubjectDetails(subjectId) {
      try {
        const response = await fetch(
          `${this.config.apiBase}/v0/subjects/${subjectId}`
        );
        if (!response.ok) return null;
        return await response.json();
      } catch (error) {
        console.error(`Error fetching subject ${subjectId}:`, error);
        return null;
      }
    }

    renderAnimeGrid() {
      const container = document.getElementById("animeGrid");
      if (!container) return;
      let html = "";

      this.animeData.forEach((anime) => {
        const progressPercent =
          anime.totalEpisodes > 0
            ? (anime.progress / anime.totalEpisodes) * 100
            : 0;

        html += `
        <div class="group relative bg-[var(--card-bg)] border border-[var(--line-divider)] rounded-[var(--radius-large)] overflow-hidden transition-all duration-300 hover:shadow-lg hover:scale-[1.02]">
          <div class="relative aspect-[2/3] overflow-hidden">
            <a href="${anime.link}" target="_blank" rel="noopener noreferrer" class="block w-full h-full">
              <img 
                src="${anime.cover}" 
                alt="${anime.title}"
                class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
                loading="lazy"
              />
              <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                <div class="absolute inset-0 flex items-center justify-center">
                  <div class="w-12 h-12 rounded-full bg-white/90 flex items-center justify-center">
                    <svg class="w-6 h-6 text-gray-800 ml-1" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M8 5v14l11-7z"/>
                    </svg>
                  </div>
                </div>
              </div>
            </a>
            
            <div class="absolute top-2 left-2 px-2 py-1 rounded-md text-xs font-medium bg-[var(--btn-regular-bg)] text-[var(--btn-content)] border border-[var(--line-divider)] backdrop-blur-sm">
              <iconify-icon icon="${anime.statusIcon}" class="mr-1 w-3 h-3"></iconify-icon>
              <span>${anime.statusText}</span>
            </div>
            
            ${
              anime.userRating > 0
                ? `
              <div class="absolute top-2 right-2 bg-[var(--btn-regular-bg)] text-[var(--btn-content)] px-2 py-1 rounded-md text-xs font-medium flex items-center gap-1 border border-[var(--line-divider)] backdrop-blur-sm">
                <iconify-icon icon="material-symbols:star" class="w-3 h-3 text-yellow-500"></iconify-icon>
                <span>${anime.userRating}</span>
              </div>
            `
                : anime.score > 0
                  ? `
              <div class="absolute top-2 right-2 bg-[var(--btn-regular-bg)] text-[var(--btn-content)] px-2 py-1 rounded-md text-xs font-medium flex items-center gap-1 border border-[var(--line-divider)] backdrop-blur-sm">
                <iconify-icon icon="material-symbols:bar-chart" class="w-3 h-3"></iconify-icon>
                <span>${anime.score}</span>
              </div>
            `
                  : ""
            }
            
            ${
              anime.status === "doing" &&
              anime.progress > 0 &&
              anime.totalEpisodes > 0
                ? `
              <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2">
                <div class="w-full bg-white/20 rounded-full h-1.5 mb-1">
                  <div class="h-1.5 rounded-full transition-all duration-300" style="width: ${Math.min(progressPercent, 100)}%; background: linear-gradient(to right, var(--primary), var(--primary));"></div>
                </div>
                <div class="text-white text-xs font-medium">
                  ${anime.progress}/${anime.totalEpisodes} (${Math.round(progressPercent)}%)
                </div>
              </div>
            `
                : ""
            }
          </div>
          
          <div class="p-3">
            <h3 class="text-sm font-bold text-black/90 dark:text-white/90 mb-1 line-clamp-2 leading-tight">${anime.title}</h3>
            ${
              anime.originalTitle && anime.originalTitle !== anime.title
                ? `
              <p class="text-black/50 dark:text-white/50 text-xs mb-1 line-clamp-1">${anime.originalTitle}</p>
            `
                : ""
            }
            ${
              anime.description
                ? `
              <p class="text-black/60 dark:text-white/60 text-xs mb-2 line-clamp-2">${anime.description}</p>
            `
                : ""
            }
            
            <div class="space-y-1 text-xs">
              <div class="flex justify-between">
                <span class="text-black/50 dark:text-white/50">${window.animePageConfig?.pagination?.year || "Year"}</span>
                <span class="text-black/70 dark:text-white/70">${anime.year || window.animePageConfig?.pagination?.unknown || "Unknown"}</span>
              </div>
              ${
                anime.totalEpisodes > 0
                  ? `
                <div class="flex justify-between">
                  <span class="text-black/50 dark:text-white/50">${window.animePageConfig?.pagination?.episodes || "Episodes"}</span>
                  <span class="text-black/70 dark:text-white/70">${anime.totalEpisodes}</span>
                </div>
              `
                  : ""
              }
              ${
                anime.rank > 0
                  ? `
                <div class="flex justify-between">
                  <span class="text-black/50 dark:text-white/50">${window.animePageConfig?.pagination?.rank || "Rank"}</span>
                  <span class="text-black/70 dark:text-white/70">#${anime.rank}</span>
                </div>
              `
                  : ""
              }
              <div class="flex flex-wrap gap-1 mt-2">
                ${anime.tags
                  .slice(0, 3)
                  .map(
                    (tag) => `
                  <span class="px-1.5 py-0.5 bg-[var(--btn-regular-bg)] text-[var(--btn-content)] rounded text-xs border border-[var(--line-divider)]">${tag}</span>
                `
                  )
                  .join("")}
              </div>
            </div>

            ${
              anime.comment
                ? `
              <div class="mt-2 pt-2 border-t border-[var(--line-divider)]">
                <p class="text-xs text-black/60 dark:text-white/60 line-clamp-2 flex items-start gap-1">
                  <iconify-icon icon="material-symbols:comment" class="w-3 h-3 mt-0.5 flex-shrink-0"></iconify-icon>
                  <span>${anime.comment}</span>
                </p>
              </div>
            `
                : ""
            }
          </div>
        </div>
      `;
      });

      container.innerHTML = html;
    }

    renderPagination() {
      if (this.totalPages <= 1) {
        document.getElementById("paginationContainer")?.classList.add("hidden");
        return;
      }

      const container = document.getElementById("pagination");
      if (!container) return;
      let html = "";

      const hasPrevPage = this.currentPage > 1;
      const hasNextPage = this.currentPage < this.totalPages;

      // 检测是否为移动端
      const isMobile = window.innerWidth < 768;

      if (isMobile) {
        // 移动端简化版本：只显示上一页、当前页、下一页
        if (hasPrevPage) {
          html += `
          <button class="page-btn-mobile btn-regular inline-flex items-center justify-center w-10 h-10 rounded-xl text-sm font-medium transition-all duration-150" data-page="${this.currentPage - 1}">
            <span>‹</span>
          </button>
        `;
        }

        // 当前页信息
        html += `
        <div class="flex items-center justify-center px-3 py-2 text-sm font-medium text-[var(--btn-content)] bg-[var(--btn-regular-bg)] rounded-xl border border-[var(--line-divider)]">
          <span>${this.currentPage}</span>
          <span class="mx-1">/</span>
          <span>${this.totalPages}</span>
        </div>
      `;

        if (hasNextPage) {
          html += `
          <button class="page-btn-mobile btn-regular inline-flex items-center justify-center w-10 h-10 rounded-xl text-sm font-medium transition-all duration-150" data-page="${this.currentPage + 1}">
            <span>›</span>
          </button>
        `;
        }
      } else {
        // 桌面端完整版本
        // 上一页按钮
        if (hasPrevPage) {
          html += `
          <button class="page-btn btn-regular inline-flex items-center gap-2 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150" data-page="1">
            <span class="hidden sm:inline">${this.config.pagination.first}</span>
          </button>
          <button class="page-btn btn-regular inline-flex items-center gap-2 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150" data-page="${this.currentPage - 1}">
            <span class="hidden sm:inline">${this.config.pagination.prev}</span>
          </button>
        `;
        }

        // 页码按钮
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(this.totalPages, startPage + 4);

        for (let page = startPage; page <= endPage; page++) {
          const isActive = page === this.currentPage;
          html += `
          <button class="page-btn px-3 py-2.5 rounded-xl text-sm font-semibold transition-all duration-150 ${
            isActive
              ? "bg-[var(--primary)] text-white shadow-lg scale-105"
              : "btn-regular"
          }" data-page="${page}">
            ${page}
          </button>
        `;
        }

        // 下一页按钮
        if (hasNextPage) {
          html += `
          <button class="page-btn btn-regular inline-flex items-center gap-2 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150" data-page="${this.currentPage + 1}">
            <span class="hidden sm:inline">${this.config.pagination.next}</span>
          </button>
          <button class="page-btn btn-regular inline-flex items-center gap-2 px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150" data-page="${this.totalPages}">
            <span class="hidden sm:inline">${this.config.pagination.last}</span>
          </button>
        `;
        }
      }

      container.innerHTML = html;

      // 页面信息
      const pageInfoEl = document.getElementById("pageInfo");
      if (pageInfoEl) {
        if (isMobile) {
          // 移动端简化页面信息
          pageInfoEl.innerHTML = `
          <span class="text-[var(--btn-content)]">${window.animePageConfig?.pagination?.total || "Total"} ${this.totalCount} ${window.animePageConfig?.pagination?.records || "records"}</span>
        `;
        } else {
          // 桌面端完整页面信息
          pageInfoEl.innerHTML = `
          <span class="text-[var(--btn-content)]">${this.config.pagination.page} ${this.currentPage} ${this.config.pagination.of} ${this.totalPages} ${this.config.pagination.total} ${this.totalCount} ${this.config.pagination.records}</span>
        `;
        }
      }

      document
        .getElementById("paginationContainer")
        ?.classList.remove("hidden");
    }

    changeFilter(status) {
      this.statusFilter = status;
      this.currentPage = 1;
      this.updateUrl();
      this.renderFilterButtons();
      this.loadData();
    }

    changePage(page) {
      this.currentPage = page;
      this.updateUrl();
      this.loadData();
      window.scrollTo({ top: 0, behavior: "smooth" });
    }

    updateUrl() {
      const params = new URLSearchParams();
      if (this.currentPage > 1) params.set("page", this.currentPage.toString());
      if (this.statusFilter !== "all") params.set("status", this.statusFilter);

      let newPath = "/anime/";
      const search = params.toString();
      const newUrl = search ? `${newPath}?${search}` : newPath;

      window.history.pushState(null, "", newUrl);
    }

    showLoading() {
      document.getElementById("loadingState")?.classList.remove("hidden");
      document.getElementById("errorState")?.classList.add("hidden");
      document.getElementById("emptyState")?.classList.add("hidden");
      document.getElementById("animeGrid")?.classList.add("hidden");
      document.getElementById("paginationContainer")?.classList.add("hidden");
    }

    showError(message) {
      document.getElementById("loadingState")?.classList.add("hidden");
      document.getElementById("errorState")?.classList.remove("hidden");
      document.getElementById("emptyState")?.classList.add("hidden");
      document.getElementById("animeGrid")?.classList.add("hidden");
      document.getElementById("paginationContainer")?.classList.add("hidden");
    }

    showEmpty() {
      document.getElementById("loadingState")?.classList.add("hidden");
      document.getElementById("errorState")?.classList.add("hidden");
      document.getElementById("emptyState")?.classList.remove("hidden");
      document.getElementById("animeGrid")?.classList.add("hidden");
      document.getElementById("paginationContainer")?.classList.add("hidden");
    }

    showDataState() {
      document.getElementById("loadingState")?.classList.add("hidden");
      document.getElementById("errorState")?.classList.add("hidden");
      document.getElementById("emptyState")?.classList.add("hidden");
      document.getElementById("animeGrid")?.classList.remove("hidden");
    }

    showUnconfiguredState() {
      document.getElementById("loadingState")?.classList.add("hidden");
      document.getElementById("errorState")?.classList.add("hidden");
      document.getElementById("emptyState")?.classList.add("hidden");
      document.getElementById("animeGrid")?.classList.add("hidden");
      document.getElementById("paginationContainer")?.classList.add("hidden");
    }
    };
  }

  // 直接初始化
  new window.AnimePageManager()
  
</script>

<style>
  .filter-container {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-start;
    margin-bottom: 24px;
  }

  .filter-tag {
    @apply inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-full cursor-pointer transition-all duration-200 outline-none;
    @apply bg-[var(--btn-regular-bg)] text-[var(--btn-content)] border border-[var(--line-divider)];
  }

  .filter-tag:hover {
    @apply bg-[var(--btn-regular-bg-hover)] text-[var(--btn-content)] border-[var(--line-divider)];
    @apply transform -translate-y-0.5 shadow-md;
  }

  .filter-tag.active {
    @apply bg-[var(--primary)] text-white border-[var(--primary)];
    @apply shadow-lg;
    box-shadow:
      0 10px 15px -3px rgba(0, 0, 0, 0.1),
      0 4px 6px -2px rgba(0, 0, 0, 0.05),
      0 0 0 1px var(--primary);
  }

  .filter-tag.active:hover {
    @apply bg-[var(--primary)] border-[var(--primary)];
    @apply transform -translate-y-0.5 shadow-xl;
    box-shadow:
      0 20px 25px -5px rgba(0, 0, 0, 0.1),
      0 10px 10px -5px rgba(0, 0, 0, 0.04),
      0 0 0 1px var(--primary);
  }

  .tag-count {
    background: rgba(255, 255, 255, 0.8);
    color: #374151;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    min-width: 20px;
    text-align: center;
  }

  .filter-tag.active .tag-count {
    background: rgba(255, 255, 255, 0.2);
    color: white;
  }

  .line-clamp-1 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .line-clamp-3 {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  /* 分页按钮主题样式优化 */
  .page-btn,
  .page-btn-mobile {
    @apply transform-gpu;
  }

  .page-btn:hover,
  .page-btn-mobile:hover {
    @apply scale-105;
  }

  .page-btn-mobile:active {
    @apply scale-95;
  }

  /* 移动端分页容器优化 */
  @media (max-width: 767px) {
    #pagination {
      @apply gap-2;
    }

    #paginationContainer {
      @apply px-2;
    }
  }

  /* 重试按钮样式 */
  #retryButton {
    @apply transform-gpu transition-all duration-200;
    @apply hover:scale-105;
  }

  /* 加载状态动画 */
  @keyframes pulse-soft {
    0%,
    100% {
      opacity: 1;
    }
    50% {
      opacity: 0.7;
    }
  }

  #loadingState {
    animation: pulse-soft 2s ease-in-out infinite;
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .animate-spin {
    animation: spin 1s linear infinite;
  }

  .border-3 {
    border-width: 3px;
  }

  .border-t-transparent {
    border-top-color: transparent;
  }

  /* 选择框美化 */
  #sortSelect:focus {
    @apply ring-2 ring-blue-500/20 border-blue-500;
  }

  #sortSelect option {
    @apply bg-white dark:bg-neutral-800 text-black dark:text-white;
  }
</style>
